package demo.demo08;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServerDemo02 {
    public static void main(String[] args) throws Exception {
//        1. 开启 ServerSocket
        ServerSocket serverSocket = new ServerSocket(9090);
//        2. 侦听 客户端 Socket
        Socket socket = serverSocket.accept();
//        3. 获取输入流
        InputStream is = socket.getInputStream();
//        4. 读取接收的文件并保存
        FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        //通知客户端接收成功
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("文件已经成功收到，OK".getBytes());

        //5. 关闭资源, 应该使用 try -catch-finally
        outputStream.close();
        fos.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}
